﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Threading;

namespace RCU_Trial
{
    public class Receiver
    {

        int listenPort;
        public Receiver()
        {
            this.listenPort = 11000;
        }
        public Receiver(int port)
        {
            this.listenPort = port;
        }

        public void Receive()
        {
            /*set connection parameters*/
            UdpClient listener = new UdpClient(listenPort);
            // listener.Client.ReceiveTimeout = 500;
            IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
            byte[] buffer;
            MemoryStream bufferStream;
            XmlSerializer deserializer = new XmlSerializer(typeof(LunabotOutputState));
            while (true)
            {
                try
                {
                    Console.WriteLine("Waiting for broadcast...\n");
                    buffer = listener.Receive(ref groupEP);
                    bufferStream = new MemoryStream(buffer);
                    Console.WriteLine("Received data! Processing...\n");
                    LunabotOutputState state = (LunabotOutputState)deserializer.Deserialize(bufferStream);
                    Console.WriteLine(state.MotorSpeedLeft.ToString() + " " + state.MotorSpeedRight.ToString());


                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message.ToString());
                }
            }
        }
    }
}
